package com.jiechuang.user.controller;


import com.github.pagehelper.PageInfo;
import com.jiechuang.common.bean.Menu;
import com.jiechuang.common.bean.addOrUpdate.MenuAddOrUpdate;
import com.jiechuang.common.util.JWTUtil;
import com.jiechuang.common.web.Code;
import com.jiechuang.common.web.Response;
import com.jiechuang.user.dto.MenuQueryInfo;
import com.jiechuang.user.service.MenuService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/menu")
public class MenuController {
    @Autowired
    private MenuService menuService;
    @Autowired
    private JWTUtil jwtUtil;
    @PostMapping("/menu")
    public Response addMenu(@RequestBody MenuAddOrUpdate menuAddOrUpdate){
        try {
            menuService.addMenu(menuAddOrUpdate);
            return new Response(Code.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Response(Code.SAVE_ERROR);
        }
    }
    @GetMapping("/list")
    public Response getMenuList(@RequestHeader("Authorization") String token){
        try {
            Claims claims = jwtUtil.parseJWT(token);
            List<String> roleCodes = (List<String>) claims.get("roleCodes");
            List<Menu> menuListByRoleIds = menuService.getMenuListByRoleCodes(roleCodes);
            return new Response(Code.SUCCESS,menuListByRoleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Response(Code.SEARCH_ERROR);
        }

    }
    @PostMapping("menus/list")
    public Response getAllMenuList(@RequestBody MenuQueryInfo menuQueryInfo){
        try {
            PageInfo<Menu> pageInfo = menuService.getMenuAllList(menuQueryInfo);
            return new Response(Code.SUCCESS,pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return new Response(Code.SEARCH_ERROR);
        }
    }
    @GetMapping("menus/{id}")
    public Response getMenu(@PathVariable Integer id){
        try {
            Menu menu=menuService.getMenu(id);
            return new Response(Code.SUCCESS,menu);
        } catch (Exception e) {
            e.printStackTrace();
            return new Response(Code.SEARCH_ERROR);
        }
    }
}
